package org.nathanielyoung.fbb;

import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.nathanielyoung.events.EventSource;

public class Lobby extends EventSource<OpponentEvent, OpponentListener> {

	private Queue<OpponentEvent> queue = new LinkedList<OpponentEvent>();
	
	public Lobby() {
		OpponentListener listener = new OpponentListener();
		this.register(listener);
	}
	
	public String whoGotNext(String player) {
		try {
			OpponentEvent challenger = queue.remove();

			OpponentEvent toWaiting = new OpponentEvent(player, challenger.getSession());
			this.fire(toWaiting);
			
			return challenger.getName();
		} catch(NoSuchElementException e) {
			return null;
		}
	}
	
	public void waitForOpponent(String player) {
		WebContext context = WebContextFactory.get();
		queue.offer(new OpponentEvent(player, context.getScriptSession()));
	}
}